﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Security;
using System.Diagnostics;

namespace XmlStudio.Logger
{
    /// <summary>
    /// Text log writer. Writes to a plain text file.
    /// </summary>
    public class TextLogWriter : ILogWriter
    {
        #region Fields
        private FileStream fileStream;
        private StreamWriter streamWriter;
        private string fileName;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the TextLogWriter class.
        /// </summary>
        /// <param name="fileName">Path to the file to log into.</param>
        /// <exception cref="System.IO.IOException">Rethrown exception.</exception>
        /// <exception cref="System.Security.SecurityException">Rethrown exception.</exception>
        /// <exception cref="System.ArgumentException">Rethrown exception.</exception>
        public TextLogWriter(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName is null or empty!");
            }

            try
            {
                lock (this)
                {
                    this.fileName = fileName;
                    this.fileStream = new FileStream(this.fileName, FileMode.Append);
                    this.streamWriter = new StreamWriter(this.fileStream);
                    this.streamWriter.AutoFlush = true;
                }
            }
            catch (IOException)
            {
                throw;
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (ArgumentException)
            {
                throw;
            }
        }
        #endregion

        #region ILogWriter Members
        /// <summary>
        /// Writes message to text file.
        /// </summary>
        /// <param name="text">Log's message.</param>
        /// <param name="level">Log's level.</param>
        /// <param name="source">Log's source, e.g. method name.</param>
        /// <param name="type">Log entry type.</param>
        public void Write(string text, int level, string source, LogType type)
        {
            lock (this)
            {
                string record = CreateMessage(text, level, source, type);
                Debug.Print(record);
                streamWriter.WriteLine(record);
            }
        }

        /// <summary>
        /// Writes exception to text file.
        /// </summary>
        /// <param name="exception">Exception to log.</param>
        /// <param name="level">Log's level.</param>
        /// <param name="source">Log's source, e.g. method name.</param>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="System.ObjectDisposedException"></exception>
        public void Write(Exception exception, int level, string source)
        {
            lock (this)
            {
                string record = CreateMessage(exception.Message + Environment.NewLine + exception.StackTrace, level, source, LogType.Exception);
                Debug.Print(record);
                streamWriter.WriteLine(record);
            }

            throw exception;
        }
        #endregion

        #region Private methods
        private static string CreateMessage(string text, int level, string source, LogType type)
        {
            string record = string.Format(CultureInfo.InvariantCulture, "{0} - [{1} - {2}]: {3} ({4})", TimeString, level, type.ToString(), text, source);
            return record;
        }
        #endregion

        #region Private properties
        private static string TimeString
        {
            get
            {
                return System.DateTime.FromFileTime(DateTime.Now.ToFileTime()).ToString();
            }
        }
        #endregion

        #region IDisposable Members
        /// <summary>
        /// Disposes of disposable items.
        /// </summary>
        public void Dispose()
        {
            if (this.streamWriter != null)
            {
                this.streamWriter.Close();
            }
        }
        #endregion
    }
}
